package com.rockcent.mall.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.common.utils.RBeanUtils;
import com.rockcent.mall.Routes;
import com.rockcent.mall.helper.TopicHelper;
import com.rockcent.mall.lib.domain.Topic;
import com.rockcent.mall.lib.domain.TopicProduct;
import com.rockcent.mall.lib.dto.TopicDto;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.repository.TopicProductRepository;
import com.rockcent.mall.lib.repository.TopicRepository;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 包含功能：
 * 新增、修改、删除、查询信息、查询列表
 * Created by zhangjh on 2016/11/15.
 */
@RestController
public class TopicController extends BaseController {

    private final Logger log = LoggerFactory.getLogger(TopicController.class);

    @Autowired
    private BaseUserHelper userHelper;


    @Autowired
    private TopicRepository topicRepository;

    @Autowired
    private TopicHelper topicHelper;

    @Autowired
    private TopicProductRepository topicProductRepository;
    @Autowired
    private ObjectMapper objectMapper;


    /**
     * @api {post} /mall/mobile/topic/save M端 新增专题
     * @apiGroup mall_mobiletopic
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {String} pic <code>必须参数</code> 专题图片
     * @apiParam {String} title <code>必须参数</code> 专题标题
     * @apiParam {String} description <code>可选参数</code> 专题描述
     * @apiParam {String} topicProducts_productId <code>必须参数</code> 产品id
     * @apiParam {String} topicProducts_seqNo <code>必须参数</code> 排序序号
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code":"1",
     *  "desc":"成功"
     * }
     */
    @RequestMapping(value = Routes.MALL_MOBILE_TOPIC_SAVE, method = RequestMethod.POST)
    @Transactional
    public JsonResult addInfo(@RequestBody TopicDto dto, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        Long mallId = userDto.mall.getId();
        RestDoing doing = jsonResult -> {
            if (dto == null) {
                jsonResult.errorParam("topic信息为空", log);
                return;
            }
            if (dto.getPic() == null) {
                jsonResult.errorParam("图片路径为空", log);
                return;
            }
            if (dto.getTitle() == null) {
                jsonResult.errorParam("标题为空", log);
                return;
            }
            if (dto.getSeqNo() == null) {
                jsonResult.errorParam("排序编号为空", log);
                return;
            }

//            if (dto.getBackgroundPath() == null) {
//                jsonResult.errorParam("背景图片为空", log);
//                return;
//            }


//            if (dto.getDescription() == null) {
//                jsonResult.errorParam("专题介绍信息为空", log);
//                return;
//            }

            Topic topic = topicHelper.chgCtoToDomain(dto);
            topic.setIsDelete(Whether.NO);
            topic.setMallId(mallId);
            topic = topicRepository.save(topic);

            List<TopicProduct> topicProducts = dto.getTopicProducts();
            List<TopicProduct> resultTopicProducts = new ArrayList<>();
            for (TopicProduct topicProduct : topicProducts) {
                topicProduct.setTopicId(topic.getId());
                topicProduct.setIsDelete(Whether.NO);

                TopicProduct topicProductNew = topicProductRepository.save(topicProduct);

                resultTopicProducts.add(topicProductNew);
            }

            dto.setTopicProducts(resultTopicProducts);
//            jsonResult.data = dto;
        };
        return doing.go(request, log);
    }


    /**
     * @api {get} /mall/mobile/topic/info M端 查询专题
     * @apiGroup mall_mobiletopic
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {String} id <code>必须参数</code> 记录id
     * @apiSuccessExample {json} Success-Response:
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *     "id": 18,
     *     "dateCreated": "2016-11-18 15:13:24",
     *     "lastUpdated": "2016-11-18 15:31:35",
     *     "mallId": 1,
     *     "title": "主题01x",
     *     "pic": "['/upload/1x.jpg','/upload/2x.jpg','/upload/3x.jpg']",
     *     "description": "主题01x",
     *     "seqNo": 1,
     *     "topicProducts": [
     *       {
     *         "id": 25,
     *         "dateCreated": "2016-11-18 15:31:35",
     *         "lastUpdated": "2016-11-18 15:31:35",
     *         "version": 0,
     *         "topicId": 18,
     *         "productId": 4,
     *         "seqNo": 3
     *       },
     *       {
     *         "id": 26,
     *         "dateCreated": "2016-11-18 15:31:35",
     *         "lastUpdated": "2016-11-18 15:31:35",
     *         "version": 0,
     *         "topicId": 18,
     *         "productId": 8,
     *         "seqNo": 4
     *       }
     *     ]
     *   }
     * }
     *
     */
    @RequestMapping(value = Routes.MALL_MOBILE_TOPIC, method = RequestMethod.GET)
    public JsonResult queryInfo(@RequestParam("id") Long id, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        Long mallId = userDto.mall.getId();
        RestDoing doing = jsonResult -> {
            if (null == id) {
                jsonResult.errorParam("ID不能为空", log);
                return;
            }
            Topic topic = topicRepository.findByIdAndIsDelete(id, Whether.NO);
            if (topic == null) {
                jsonResult.errorParam("加载topic信息失败", log);
                return;
            }
            Long mallIdDb = topic.getMallId();
            if (mallId != mallIdDb) {
                jsonResult.errorParam("没查询权限", log);
                return;
            }

            List<TopicProduct> topicProducts = topicProductRepository.findAllByTopicId(id);

            TopicDto dto = new TopicDto();
            String pic = topic.getPic();
            if(StringUtils.isNotBlank(pic)){
                List<String> picList = objectMapper.readValue(pic, new TypeReference<List<String>>() {
                });
                dto.setPicList(picList);
            }


            RBeanUtils.copyProperties(topic,dto);
            dto.setTopicProducts(topicProducts);

            jsonResult.data = dto;

        };
        return doing.go(request, log);

    }


    /**
     * @api {put} /mall/mobile/topic/delete/ M端 删除专题
     * @apiGroup mall_mobiletopic
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {String} id <code>必须参数</code> 记录id
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code":"1",
     *  "desc":"成功"
     * }
     */
    @RequestMapping(value = Routes.MALL_MOBILE_TOPIC_DELETE, method = RequestMethod.PUT)
    @Transactional
    public JsonResult deleteInfo(@RequestBody TopicDto dto, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        Long mallId = userDto.mall.getId();
        RestDoing doing = jsonResult -> {
            Long id = dto.getId();
            if (null == id) {
                jsonResult.errorParam("ID不能为空", log);
                return;
            }
            Topic topic = topicRepository.findByIdAndIsDelete(id, Whether.NO);
            if (topic == null) {
                jsonResult.errorParam("加载topic信息失败", log);
                return;
            }
            Long mallIdDb = topic.getMallId();
            if (mallId != mallIdDb) {
                jsonResult.errorParam("没有删除权限", log);
                return;
            }
            topic.setIsDelete(Whether.YES);
            topicRepository.save(topic);
            topicProductRepository.deleteByTopicId(id);
        };
        return doing.go(request, log);
    }


    /**
     * @api {put} /mall/mobile/topic/update M端 修改专题
     * @apiGroup mall_mobiletopic
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {Long} id <code>必须参数</code> 记录id
     * @apiParam {String} pic <code>必须参数</code> 专题图片
     * '["/upload/1.jpg","/upload/2.jpg","/upload/3.jpg"]'
     * @apiParam {String} title <code>必须参数</code> 专题标题
     * @apiParam {String} description <code>可选参数</code> 专题描述
     * @apiParam {String} topicProducts_productId <code>必须参数</code> 产品id
     * @apiParam {String} topicProducts_seqNo <code>必须参数</code> 排序序号
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code":"1",
     *  "desc":"成功"
     * }
     */
    @RequestMapping(value = Routes.MALL_MOBILE_TOPIC_UPDATE, method = RequestMethod.PUT)
    @Transactional
    public JsonResult updateInfo(@RequestBody TopicDto dto, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        Long mallId = userDto.mall.getId();
        RestDoing doing = jsonResult -> {
            if (dto == null) {
                jsonResult.errorParam("topic信息为空", log);
                return;
            }
            Long id = dto.getId();
            if (dto.getId() == null) {
                jsonResult.errorParam("记录id为空", log);
                return;
            }
            if (dto.getPic() == null) {
                jsonResult.errorParam("专题图片地址为空", log);
                return;
            }
            if (dto.getTitle() == null) {
                jsonResult.errorParam("标题为空", log);
                return;
            }
            if (dto.getSeqNo() == null) {
                jsonResult.errorParam("排序编号为空", log);
                return;
            }

            Topic topic = topicRepository.findByIdAndIsDelete(id, Whether.NO);
            if (topic == null) {
                jsonResult.remind(topic.REMIND_RECORD_IS_NOT_EXIST,log);;
                return;
            }
            Long mallIdDb = topic.getMallId();
            if (mallId != mallIdDb) {
                jsonResult.errorParam("没修改权限", log);
                return;
            }
            String title = dto.getTitle();
            if (StringUtils.isNotBlank(title)) {
                topic.setTitle(title);
            }

            String picPath = dto.getPic();
            if (StringUtils.isNotBlank(picPath)) {
                topic.setPic(picPath);
            }

            String url = dto.getUrl();
            if (StringUtils.isNotBlank(url)) {
                topic.setUrl(url);
            }

            String description = dto.getDescription();
            if (StringUtils.isNotBlank(description)) {
                topic.setDescription(description);
            }

            String backgroundPath = dto.getBackgroundPath();
            if (StringUtils.isNotBlank(backgroundPath)) {
                topic.setBackgroundPath(backgroundPath);
            }

            Integer seqNo = dto.getSeqNo();
            if(null!=seqNo){
                topic.setSeqNo(seqNo);
            }


            topicRepository.save(topic);
            topicProductRepository.deleteByTopicId(id);

            List<TopicProduct> topicProducts = dto.getTopicProducts();
//            List<TopicProduct> resultTopicProducts = new ArrayList<>();
            for (TopicProduct topicProduct : topicProducts) {
                topicProduct.setTopicId(id);
                TopicProduct topicProductNew = topicProductRepository.save(topicProduct);
//                resultTopicProducts.add(topicProductNew);
            }

//            jsonResult.data = topic;
        };
        return doing.go(request, log);
    }


    /**
     * @api {get} /mall/mobile/topic/list M端 搜索专题
     * @apiGroup mall_mobiletopic
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {String} title <code>可选参数</code> 标题
     * @apiParam {String} startDate <code>可选参数</code> 开始时间
     * @apiParam {String} endDate <code>可选参数</code> 结束时间
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code":"1",
     *     "desc":"成功",
     *     "data":{
     *         "data":[
     *             {
     *                 "id":23,
     *                 "dateCreated":"2016-11-18 16:50:22",
     *                 "lastUpdated":"2016-11-18 16:50:22",
     *                 "mallId":1,
     *                 "title":"主题01",
     *                 "pic":"['/upload/1.jpg','/upload/2.jpg','/upload/3.jpg']",
     *                 "description":"主题01",
     *                 "seqNo":1,
     *                 "productsCount":0
     *             },
     *             {
     *                 "id":22,
     *                 "dateCreated":"2016-11-18 15:27:11",
     *                 "lastUpdated":"2016-11-18 15:27:11",
     *                 "mallId":1,
     *                 "title":"主题01",
     *                 "pic":"['/upload/1.jpg','/upload/2.jpg','/upload/3.jpg']",
     *                 "description":"主题01",
     *                 "seqNo":1,
     *                 "productsCount":2
     *             }
     *         ],
     *         "totalCount":2,
     *         "totalPage":1,
     *         "pageNo":0,
     *         "pageSize":10
     *     }
     * }
     *
     */
    @RequestMapping(value = Routes.MALL_MOBILE_TOPIC_LIST, method = RequestMethod.GET)
    public JsonResult listInfo(TopicDto dto, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        Long mallId = userDto.mall.getId();
        RestDoing doing = jsonResult -> {
            if (dto == null) {
                jsonResult.errorParam("topic信息为空", log);
                return;
            }
            String title = dto.getTitle();

            String beginDate = dto.getBeginDate();
            String endDate = dto.getEndDate();
            Integer pageNo = dto.getPageNo();
            Integer pageSize = dto.getPageSize();
            PageResult<TopicDto> pageResult = topicRepository.findTopicQuery(mallId, title, beginDate, endDate, Whether.NO, this.getPage(pageNo, pageSize));

            if(null!=pageResult.data && pageResult.data.size()>0){
                for (TopicDto topic : pageResult.data) {
                    Long topicId = topic.getId();
                    List<TopicProduct> topicProducts = topicProductRepository.findAllByTopicId(topicId);
                    if (null != topicProducts) {
                        topic.setProductsCount(topicProducts.size());
                    }
                }

            }
            jsonResult.data = pageResult;

        };
        return doing.go(request, log);
    }


}
